<?php
function var_register($name, $default = false)
{
	if(isset($_GET[$name])) {
		if(function_exists("shrink_validate_$name")) {
			if(call_user_func("shrink_validate_$name", $_GET[$name])) {
				return $_GET[$name];
			} else {
				return $default;
			}
		}
		
		if(function_exists("shrink_format_$name")) {
			return call_user_func("shrink_format_$name", $_GET[$name]);
		} else {
			return $_GET[$name];
		}
	}
	
	return $default;
}

function shrink_validate_action($action)
{
	$allowed_values = array('add', 'edit', 'delete', 'Open', 'Close');
	if(!in_array($action, $allowed_values)) {
		return false;
	}
	
	return true;
}

function shrink_validate_id($id)
{
	return preg_match('/[A-Za-z0-9\*]{32}/', $id);
}

function shrink_validate_state($state)
{	
	$allowed_values = array('open', 'closed', 'all');
	if(!in_array($state, $allowed_values)) {
		return false;
	}
	return true;
}

function shrink_format_date($ts)
{
	return date("d/m/Y", strtotime(substr($ts, 0, 10)));
}

function shrink_format_body($s)
{
	include_once 'Library/Markdown/markdown.php';
	$s = shrink_wikize($s);
	return Markdown(ltrim($s));
}

function shrink_format_subject($s)
{
	if(strlen($s)>32) {
		return substr($s, 0, 32)."&hellip;";
	} else {
		return $s;
	}
}

function shrink_show_bugs()
{
	global $db;
	$state = var_register('state', 'open');
	
	
	if($state == 'all') {
		$open_bugs = $db->view("_all_docs")->documents();
	} else {
		$view = $db->newView();
		$qstate = ucfirst($state);
		$view->function = "function(doc) { if(doc.State == '$qstate') return doc; }";
		$open_bugs = $view->documents();  // $state, $options = array('reverse' => 'true'));
	}
	if(($open_bugs !== false) && (count($open_bugs) > 0)) {
		foreach($open_bugs AS $bug) {
			if(strlen($bug->Subject) == 0) {continue;}
			$id = $bug->id();
			$bug->set('CreationDate', shrink_format_date($bug->get('CreationDate')));
			$showState = ('all' == $state)?$bug->get("State"):'';
			$icon = shrink_get_icon($bug->get('State'));
			$Subject = shrink_format_subject($bug->get('Subject'));
			$Project = $bug->get('Project');
			$Category = $bug->get('Category');
			$Author = $bug->get('Author');
			echo <<<EOD
			<div class="bug list">
				<div class="Subject">
					<span class="$bug->State">$icon</span>
					<a href="?id=$id">[$Project $Category] $Subject</a>
				</div>
					
				<div class="bugDetails">
					(<a href="?action=edit&id=$id">edit</a>)
					<em>reported by</em>&ensp;$Author
					<em>on</em>&ensp;$bug->CreationDate
					$showState
				</div>
			</div>
EOD;
		}
	} else {
		echo "<div id=\"noBugs\">No $state Bugs Found</div>";
	}
}

function shrink_show_bug_details($bug_details)
{
	$id = $bug_details->id();

	$bug_details->set('CreationDate', shrink_format_date($bug_details->get('CreationDate')));
	$icon = ($bug_details->get('State') == 'Open')?'&dagger;':'&radic;';
	$quickAction = ($bug_details->get('State') == 'Closed')?'Open':'Close';
	$Body = shrink_format_body($bug_details->get('Body'));
	$Subject = ($bug_details->get('Subject'));
	$Project = $bug_details->get('Project');
	$Category = $bug_details->get('Category');
	echo <<<EOD
	<hr>
<div class="bug">
	<div class="Subject">
		<span class="$bug_details->State">$icon</span>
		[$Project $Category] $Subject
	</div>

	<div class="bugDetails">
		<em>reported by</em>&ensp;$bug_details->Author
		<em>on</em>&ensp;$bug_details->CreationDate
		State: $bug_details->State
	</div>

	<div class="desc">
		$Body
	</div>

	<a href="?action=edit&id=$id">Edit this Bug</a> | <a href="?action=$quickAction&id=$id">$quickAction this Bug</a> | <a href="?action=delete&id=$id" onClick="return confirm('Are you sure?')">Delete this Bug</a> 
</div>
EOD;
	
}

function shrink_get_icon($State)
{
	switch($State) {
		case 'Open':
			return '&dagger;';
		break;
		
		case 'Closed':
			return '&radic';
		break;
		
		default:
			return '';
		break;
	}

}

// function shrink_toggle_status($id, $status)
// {
// 	global $couch;
// 	
// 	$couch->update($id, array('State' => $status));
// }

function shrink_wikize($s)
{
	return preg_replace("/\[\[([^\]]+)\]\]/", "<em><a href=\"?id=$1\">#$1</a></em>", $s);
}

function shrink_save_meta($Project, $Category)
{
	// _shrink_do_save_meta($Project, $type = 'Project');
	// _shrink_do_save_meta($Category, $type = 'Category');
}

function _shrink_do_save_meta($name, $type)
{
 	global $db;
 	$BugId = strtoupper(md5($name));
//	echo "saving $name to $id as $type";
	// if($doc = $db->view('_all_docs')->documents()) {//(strtolower('add'.$type), $options = array('key' => $BugId))) {
	// 	list($id, $doc) = each($doc);
	// 	$doc->set('Counter', $doc->get('Counter') + 1); // Count++
	// 	$doc->save();
	// } else {
	// 	$doc = $db->newDocument();
	// 	$doc->set('BugId', $BugId);
	// 	$doc->set('Name', $name);
	// 	$doc->set('Counter', 1);
	// 	$doc->set('Type', $type);
	// 	$doc->save();
	// }
	
}

function shrink_show_meta($type, $current, $limit = 0)
{
	global $db;
	$view = $db->newView();
	switch($type) {
		case "Projects":
			$qtype = "Project";
			$jstype = 'projects';
		break;
		
		case "Categories":
			$qtype = "Category";
			$jstype = 'categories';
		break;
	}
	
	$view->function = "function(doc) { if(doc.$qtype) return doc.$qtype; }";
//	var_dump($view->function);
	$docs = $view->documents();//($type, $options = array('reverse' => 'true'));
	
	// var_dump($docs);
	if(!$docs || (count($docs) == 0)) {
		?><li>No <?=$type?> found.</li><?
	} else {
		$counter = 0;
		$done = array();
		foreach($docs AS $doc) {
			$active = $checked = '';
			$name = $doc->get($qtype);
			if((strlen($name) == 0) || in_array(strtolower($name), $done)) {
				continue;
			}
			$done[] = strtolower($name);

			if(strCaseCmp($current, $name) == 0) {
				$active = ' style="font-weight:bold;"';
				$checked = ' checked="checked"';
			} 
			$onClick = 'onClick="setMeta(\''.$name.'\', \''.$type.'\');return false;"';
			?>
			<li>
				 <input type="radio" name="meta_<?=$type?>" value="<?=$type?>_<?=$name?>" id="<?=$type?>_<?=$name?>" <?=$onClick?> class="bug_meta"<?=$checked?>>
				<a<?=$active?> name="meta_<?=$type?>" id="meta_<?=$type?>_<?=$name?>" href="#" <?=$onClick?>><?=$name?></a>
				</li>
			<?php

			$counter++;
			if($counter == $limit) {
				break;
			}
		}
	}
}

function shrink_show_projects($current, $limit = 0)
{
	shrink_show_meta('Projects', $current, $limit);
}

function shrink_show_categories($current, $limit = 0)
{
	shrink_show_meta('Categories', $current, $limit);
}